<script setup>
import {defineProps, ref, defineEmits, watch} from "vue";
import {listSchool} from "../../../api/user/school.js";
import {listStudent} from "../../../api/user/user.js";
import {inviteStudent, listCourseStudent, updateCourseNumber} from "../../../api/course/course.js";
import {ElMessage} from "element-plus";

const props = defineProps(["isInsertClass","classId"]);
const courseId = ref();
courseId.value=localStorage.getItem("courseId");

// 事件获取
const emit = defineEmits(['close']);
// 是否显示弹窗
const isInsertStudent = ref(false);
isInsertStudent.value = props.isInsertClass;
// 多选
const multipleTableRef = ref();
// 选择条件
const condition = ref({
  username: '',
  schoolName: '',
});
// 单位
const school = ref([{
  id: '',
  name: '',
}]);
// 学生信息
const student = ref([])

// 班级学生对象
const studentClass = ref([])

// 取消按钮
const handleCancel = () => {
  emit('close');
  isInsertStudent.value = false;
}

watch(() => props.isInsertClass, (newVal) => {
  isInsertStudent.value = newVal;
});

// 搜索单位(可以学习一下)
const handleListSchool = async (queryString, cb) => {
  try {
    // console.log(queryString);
    const res = await listSchool({schoolName: queryString});
    if (res && res.data) {
      school.value = res.data.map(item => ({
        value: item.schoolName,
        id: item.id
      }));
      cb(school.value);
    } else {
      cb([]);
    }
  } catch (error) {
    console.error("Error fetching school list:", error);
    cb([]);
  }
};


// 点击选中项触发
const handleSelect = (item) => {
  condition.value.schoolName = item.value;
}

// 搜索学生
const handleListStudent = async () => {
  await listStudent(condition.value).then(res => {
    student.value = res.data;
    // console.log(student.value);
  })
}

// 添加学生
const handleInviteStudent = async () => {
  studentClass.value=[];
  console.log(multipleTableRef.value.length);
  for(let i=0;i<multipleTableRef.value.length;i++){
    studentClass.value.push({
      classId:props.classId,
      studentId:multipleTableRef.value[i].id,
    })
  }
  // console.log(studentClass.value);
  await inviteStudent(studentClass.value).then(()=>{
    emit('close');
    ElMessage.success('邀请学生成功');
    student.value=[];
    handleUpdateCourseNumber();
  })
}

// 修改课程成员数量
const handleUpdateCourseNumber = async () => {
  console.log(studentClass.value.length,courseId.value);
  await updateCourseNumber(Number(courseId.value),{number:studentClass.value.length})
}


// 选中学生
const handleSelectionChange = (val) => {
  multipleTableRef.value=val;
  // console.log(multipleTableRef.value);
}
</script>

<template>
  <el-dialog
      v-model="isInsertStudent"
      title="添加学生"
      width="1200px"
      style="height: 500px; position: relative;"
      align-center
  >
    <el-form
        label-width="auto"
        :model="condition"
        :inline="true"
    >
      <el-form-item label="学生名称">
        <el-input v-model="condition.username"/>
      </el-form-item>
      <el-form-item label="学校：">
        <el-autocomplete
            v-model="condition.schoolName"
            :fetch-suggestions="handleListSchool"
            placeholder="请输入单位名称"
            @select="handleSelect"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="display: flex;justify-content: flex-end;" @click="handleListStudent">搜索
        </el-button>
      </el-form-item>
    </el-form>
    <div class="bottom-buttons">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleInviteStudent">确认</el-button>
    </div>
    <el-table
        ref="multipleTableRef"
        :data="student"
        style="width: 100%;height: 40vh"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="username" label="姓名"/>
      <el-table-column prop="phone" label="手机"/>
      <el-table-column prop="no" label="学号"/>
      <el-table-column prop="schoolName" label="学校"/>
      <el-table-column prop="updateTime" label="最后登录时间"/>
    </el-table>
  </el-dialog>
</template>

<style scoped lang="less">
.bottom-buttons {
  position: absolute;
  bottom: 20px; /* Adjust this value to add some space from the bottom */
  right: 20px; /* Adjust this value to add some space from the right */
}
</style>
